#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 crane <crane@gosun>
#
# Distributed under terms of the MIT license.

"""

"""

class MinJump:
    def __init__(self, input_str):
        self.key_alpha = "ASDFGH"
        self.key_len = len(self.key_alpha)

        self.arrange_used = self.key_len * [0]

        self.input_str = input_str

        self.min_dis = 999999999
        self.min_layout = ""

    def brute_all(self):
        self.arrange_rec("", self.key_len)

    def arrange_rec(self, layout_path, remain):
        if remain == 0:
            # print(layout_path)
            self.calc_layout_dis(layout_path)

        cnt = 0
        for idx in range(self.key_len):
            if cnt == remain:
                break

            if not self.arrange_used[idx]:
                self.arrange_used[idx] = 1
                cnt += 1

                self.arrange_rec(layout_path + self.key_alpha[idx], remain-1)

                self.arrange_used[idx] = 0

    def calc_layout_dis(self, layout):
        letter_pos = {}
        for idx, key in enumerate(layout):
            letter_pos[key] = idx

        total_dis = 0
        cur_pos = 0                # 手指起始位置
        for key in self.input_str:
            next_pos = letter_pos[key]
            total_dis += self.jump_dis(cur_pos, next_pos)
            cur_pos = next_pos

        # print(total_dis)
        if total_dis < self.min_dis:
            self.min_dis = total_dis
            self.min_layout = layout

        self.min_dis = min(self.min_dis, total_dis)


    def jump_dis(self, cur_pos, next_pos):
        return abs(cur_pos - next_pos)

def test():
    s = MinJump("ASDFGH")
    s.brute_all()
    assert s.min_dis == 5

    s = MinJump("H")
    s.brute_all()
    assert s.min_dis == 0

    s = MinJump("ASDFDSAG")
    s.brute_all()
    assert s.min_dis == 8



def main():
    # print("start main")
    test()

if __name__ == "__main__":
    main()
